package com.qianfeng.zmt.controller;

import com.qianfeng.entity.dto.GoodsSku;
import com.qianfeng.entity.dto.Order;
import com.qianfeng.entity.po.LoginMerchant;
import com.qianfeng.entity.vo.MyPage;
import com.qianfeng.http.Result;
import com.qianfeng.service.impl.GoodsService;
import com.qianfeng.service.impl.GoodsSkuService;
import com.qianfeng.service.impl.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("order")
public class OrderController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private OrderService orderService;


    @RequestMapping("new")
    public String newOrder(@RequestParam(value = "goodsId" , required = true) Long goodsId , Model model){
        model.addAttribute("goods" , goodsService.getById(goodsId) );
        model.addAttribute("skuList" , goodsSkuService.getByGoodsId(goodsId));
        model.addAttribute("buyerNum" , orderService.getCountByGoodsId(goodsId));
        return "order/new";
    }

    @RequestMapping("getPrice")
    @ResponseBody
    public Result<?> getPrice(@RequestParam(value = "skuId" , required = true) Long skuId){
        GoodsSku goodsSku = goodsSkuService.getById(skuId);
        int price = Integer.parseInt(goodsSku.getPrice());
        return Result.success(price);
    }

    @RequestMapping("createOrder")
    @ResponseBody
    public Result<?> createOrder(Order order , LoginMerchant loginMerchant){
        orderService.saveOrder(order , loginMerchant.getId());
        return Result.success();
    }

    @RequestMapping("list")
    public String list(Model model , LoginMerchant loginMerchant ,
                       @RequestParam(value = "pageNum" , required = false , defaultValue = "1") Long pageNum){
        MyPage<Order> myPage = orderService.getByMerchantId(loginMerchant.getId(), pageNum);
        model.addAttribute("orderList" , myPage.getObjList());
        model.addAttribute("pageList" , myPage.getPageList());
        return "order/list";
    }

}
